﻿
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using StudentManagement.Models;
using System;
using System.IO;

namespace StudentManagement.Controllers
{
    //[Route("[controller]")]
    public class HomeController : Controller
    {
        private readonly IStudentRepository _studentRepository;
        private readonly IWebHostEnvironment hostEnviroment;
        private readonly ILogger logger;

        public HomeController(IStudentRepository studentRepository,IWebHostEnvironment hostEnvironment,ILogger<HomeController> logger)
        {
            _studentRepository = studentRepository;
            this.hostEnviroment = hostEnvironment;
            this.logger = logger;
  
        }
        //[Route("/")]
        //[Route("[action]")]
        public IActionResult Index()
        {
            return View(_studentRepository.GetAllStudents());
        }
        //[Route("[action]/{id?]")]
        public IActionResult Details(int id)
        {
            logger.LogInformation("此异常发生在Details视图中");

            var student = _studentRepository.GetStudent(id);
            if (student==null)
            {
                Response.StatusCode = 404;
                return View("StudentNotFound",id);
            }
            HomeDetailsViewModel model = new()
            {
                Student = student,
                Title="学生详细信息"
            };
            return View(model);
        }
        [HttpGet]
        public IActionResult Create()
        {
            return View();
        }
        [HttpPost]
        public IActionResult Create(StudentCreateViewModel model)
        {
            if (ModelState.IsValid)
            {
                string uniqueFileName = string.Empty;
                if(model.Photos!=null && model.Photos.Count>0)
                    uniqueFileName = ProcessUploadedFile(model);

                Student newStu = new()
                {
                    Name = model.Name,
                    Email = model.Email,
                    ClassName = model.ClassName,
                    PhotoPath = uniqueFileName
                };
                _studentRepository.Add(newStu);
                return RedirectToAction("Details", new { id = newStu.Id });
            }
            return View();
        }

        [HttpGet]
        public ViewResult Edit(int id)
        {
            var student = _studentRepository.GetStudent(id);
            StudentEditViewModel studentEditViewModel = new()
            {
                Id = student.Id,
                Name = student.Name,
                Email = student.Email,
                ClassName = student.ClassName,
                ExistingPhotoPath = student.PhotoPath
            };
            return View(studentEditViewModel);
        }

        [HttpPost]
        public IActionResult Edit(StudentEditViewModel model)
        {
            if (ModelState.IsValid)
            {
                Student student=_studentRepository.GetStudent(model.Id);
                student.Email = model.Email;
                student.ClassName = model.ClassName;
                student.Name = model.Name;

                if(model.Photos.Count>0)
                {
                    if(!string.IsNullOrWhiteSpace( model.ExistingPhotoPath))
                    {
                        string filePath=Path.Combine(hostEnviroment.WebRootPath,"Images",model.ExistingPhotoPath);
                        System.IO.File.Delete(filePath);
                    }

                    student.PhotoPath = ProcessUploadedFile(model);
                }

                Student updateStudent = _studentRepository.Update(student);
                return RedirectToAction("Index");
            }
            return View();
        }

        /// <summary>
        /// 将图片保存，并返回唯一文件路径
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        private string ProcessUploadedFile(StudentCreateViewModel model)
        {
            string uniqueFileName = string.Empty;
            if (model.Photos.Count > 0)
                foreach (var photo in model.Photos)
                {
                    string uploadsFolder = Path.Combine(hostEnviroment.WebRootPath, "Images");
                    uniqueFileName = Guid.NewGuid().ToString() + "_" + photo.FileName;
                    string filePath = Path.Combine(uploadsFolder, uniqueFileName);
                    using var fileStream = new FileStream(filePath, FileMode.Create);
                    photo.CopyTo(fileStream);
                }
            return uniqueFileName;
        }
    }
}
